package com.demo.utils;



import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class CipherTest {
    private static String  key="12345678123456781234567812345678";
    /**
     * 解密字符串
     *
     * */
    public static String descrpte(String enPassword) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
        byte[] encrypted1 =Base64.getDecoder().decode(enPassword);
        SecretKeySpec secretKeySpec=new SecretKeySpec(encrypted1,"DESede");

        Cipher cipher=Cipher.getInstance("DESede");
        cipher.init(Cipher.DECRYPT_MODE,secretKeySpec);
        byte[]  descrpteByte=cipher.doFinal(enPassword.getBytes("UTF-8"));
        return  new String(descrpteByte,"UTF-8");
    }
    /**
     * 加密字符串
     * */
    public static String encrypt(String enPassword) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
        byte[] encrypted1 =Base64.getDecoder().decode(enPassword);
        SecretKeySpec secretKeySpec=new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8),"DESede");

        Cipher cipher=Cipher.getInstance("DESede");
        cipher.init(Cipher.ENCRYPT_MODE,secretKeySpec);
        byte[]  ecncrptByte=cipher.doFinal(enPassword.getBytes("UTF-8"));
        return  new String(ecncrptByte,"UTF-8");
    }

    public static void main(String[] args) throws NoSuchPaddingException, BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, UnsupportedEncodingException, InvalidKeyException {
        String  str="123";
        String encrypt=encrypt(str);
        String plaint=descrpte(encrypt);

        System.out.println("加密后的字符串："+encrypt);
        System.out.println("解密后的字符串："+plaint);
    }
}
